package flc.ast.activity;

import static com.stark.imgocr.api.VerifyMethod.APPCODE;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.os.Bundle;
import android.view.View;

import com.blankj.utilcode.util.ToastUtils;
import com.otaliastudios.cameraview.BitmapCallback;
import com.otaliastudios.cameraview.CameraException;
import com.otaliastudios.cameraview.CameraListener;
import com.otaliastudios.cameraview.CameraOptions;
import com.otaliastudios.cameraview.PictureResult;
import com.otaliastudios.cameraview.VideoResult;
import com.otaliastudios.cameraview.controls.Audio;
import com.otaliastudios.cameraview.controls.Flash;
import com.otaliastudios.cameraview.controls.Mode;
import com.otaliastudios.cameraview.size.SizeSelector;
import com.otaliastudios.cameraview.size.SizeSelectors;
import com.stark.imgedit.utils.Matrix3;
import com.stark.imgedit.view.imagezoom.ImageViewTouchBase;
import com.stark.imgocr.ImgOcrEntry;
import com.stark.imgocr.api.Config;
import com.stark.imgocr.api.IRetCallback;
import com.stark.imgocr.api.bean.OcrRetBean;

import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.databinding.ActivityPhotoRecBinding;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.utils.DensityUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.StkPermissionHelper;

public class PhotoRecActivity extends BaseAc<ActivityPhotoRecBinding> {

    private boolean isFlash = false;//判断是否打开闪光灯
    private boolean isTaken = false;//判断是否拍照
    private Bitmap mRetBitmap;


    @Override
    protected int onCreate() {
        return R.layout.activity_photo_rec;
    }

    @Override
    protected boolean isStatusBarTextDark() {
        return false;
    }

    @Override
    public void onBackPressed() {
        if (isTaken) {
            isTaken = false;
            mDataBinding.cameraView.setVisibility(View.VISIBLE);
            mDataBinding.imageViewTouch.setVisibility(View.GONE);
            mDataBinding.cropImgView.setVisibility(View.GONE);
            mDataBinding.llCamera.setVisibility(View.VISIBLE);
            mDataBinding.ivStartRec.setVisibility(View.GONE);
        } else {
            finish();
        }
    }

    @Override
    protected void initView() {
        mDataBinding.ivPhotoRecBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.imageViewTouch.setDisplayType(ImageViewTouchBase.DisplayType.FIT_TO_SCREEN);
        mDataBinding.imageViewTouch.setScaleEnabled(false);// 禁用缩放


        mDataBinding.llFlash.setOnClickListener(this);
        mDataBinding.ivTakePhoto.setOnClickListener(this);
        mDataBinding.ivStartRec.setOnClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.llFlash://手电筒
                openFlash();
                break;
            case R.id.ivTakePhoto://拍照
                mDataBinding.cameraView.takePictureSnapshot();
                break;
            case R.id.ivStartRec://开始识别
                applyCropImage();
                break;
        }
    }

    @Override
    protected void initData() {
        getPermission();
    }

    private void getPermission() {
        StkPermissionHelper.permission(Manifest.permission.CAMERA).reqPermissionDesc(getString(R.string.get_camera_permission)).callback(new StkPermissionHelper.ACallback() {
            @Override
            public void onGranted() {
                //初始化相机
                initCameraView();
            }

            @Override
            public void onDenied(boolean needGoSettings) {
                ToastUtils.showShort(R.string.no_permission);
            }
        }).request();
    }

    //初始化相机
    private void initCameraView() {
        mDataBinding.cameraView.setMode(Mode.PICTURE);
//        mDataBinding.cameraView.setAudio(Audio.OFF);
        mDataBinding.cameraView.setLifecycleOwner(this);
        int width = DensityUtil.getWith(mContext);
        int height = DensityUtil.getHeight(mContext);
        SizeSelector maxAreaSelector = SizeSelectors.maxArea(width * height);
        SizeSelector equalWidthSelector = SizeSelectors.withFilter(size -> size.getWidth() == width);
        mDataBinding.cameraView.setPictureSize(SizeSelectors.and(maxAreaSelector, equalWidthSelector));
        mDataBinding.cameraView.addCameraListener(new CameraListener() {
            @Override
            public void onCameraOpened(@NonNull CameraOptions options) {

            }

            @Override
            public void onCameraClosed() {
            }

            @Override
            public void onCameraError(@NonNull CameraException exception) {
            }

            @Override
            public void onPictureTaken(@NonNull PictureResult result) {
                int width = result.getSize().getWidth();
                int height = result.getSize().getHeight();
                int screenWidth = DensityUtil.getWith(mContext);
                int screenHeight = DensityUtil.getHeight(mContext);
                if (width * height > screenWidth * screenHeight) {
                    width = screenWidth;
                    height = screenHeight;
                }
                result.toBitmap(width, height, new BitmapCallback() {
                    @Override
                    public void onBitmapReady(@Nullable Bitmap bitmap) {
                        mDataBinding.imageViewTouch.setImageBitmap(bitmap);
                        mRetBitmap = bitmap;
                        mDataBinding.cameraView.setVisibility(View.GONE);
                        mDataBinding.imageViewTouch.setVisibility(View.VISIBLE);
                        mDataBinding.imageViewTouch.post(new Runnable() {
                            @Override
                            public void run() {
                                final RectF r = mDataBinding.imageViewTouch.getBitmapRect();
                                mDataBinding.cropImgView.setCropRect(r);
                            }
                        });
                        mDataBinding.cropImgView.setVisibility(View.VISIBLE);
                        isTaken = true;
                        mDataBinding.llCamera.setVisibility(View.GONE);
                        mDataBinding.ivStartRec.setVisibility(View.VISIBLE);
                    }
                });
            }

            @Override
            public void onVideoRecordingStart() {

            }

            @Override
            public void onVideoRecordingEnd() {

            }

            @Override
            public void onVideoTaken(@NonNull VideoResult result) {

            }
        });
    }

    //打开闪光灯
    private void openFlash() {
        if (isFlash) {
            isFlash = false;
            mDataBinding.ivFlash.setImageResource(R.drawable.ashoudiantkai);
            mDataBinding.tvFlash.setTextColor(Color.parseColor("#FFFFFF"));
            mDataBinding.tvFlash.setText(getString(R.string.flash_open));
            mDataBinding.cameraView.setFlash(Flash.OFF);
        } else {
            isFlash = true;
            mDataBinding.ivFlash.setImageResource(R.drawable.aguan);
            mDataBinding.tvFlash.setTextColor(Color.parseColor("#808080"));
            mDataBinding.tvFlash.setText(getString(R.string.flash_close));
            mDataBinding.cameraView.setFlash(Flash.TORCH);
        }
    }

    public void applyCropImage() {
        showDialog(getString(com.stark.common.res.R.string.handling));
        RxUtil.create(new RxUtil.Callback<Bitmap>() {
            @Override
            public void doBackground(ObservableEmitter<Bitmap> emitter) {
                RectF cropRect = mDataBinding.cropImgView.getCropRect();// 剪切区域矩形
                Matrix touchMatrix = mDataBinding.imageViewTouch.getImageViewMatrix();
                float[] data = new float[9];
                touchMatrix.getValues(data);// 底部图片变化记录矩阵原始数据
                Matrix3 cal = new Matrix3(data);// 辅助矩阵计算类
                Matrix3 inverseMatrix = cal.inverseMatrix();// 计算逆矩阵
                Matrix m = new Matrix();
                m.setValues(inverseMatrix.getValues());
                m.mapRect(cropRect);// 变化剪切矩形

                Bitmap resultBit = Bitmap.createBitmap(mRetBitmap, (int) cropRect.left, (int) cropRect.top, (int) cropRect.width(), (int) cropRect.height());
                emitter.onNext(resultBit);
            }

            @Override
            public void accept(Bitmap bitmap) {
                if (bitmap != null) {
                    Config config;
                    config = Config.verifyByAppCode(String.valueOf(APPCODE));
                    ImgOcrEntry.init(config);
                    ImgOcrEntry.getOcrReqManager().urlImages(PhotoRecActivity.this, bitmap, new IRetCallback<List<OcrRetBean.Word>>() {
                        @Override
                        public void onRet(String errCode, String errMsg, @Nullable List<OcrRetBean.Word> wordList) {
                            if (isDestroyed()) {
                                return;
                            }
                            if (wordList == null) {
                                ToastUtils.showShort(errMsg);
                                return;
                            }
                            StringBuilder stringBuilder = new StringBuilder();
                            OcrRetBean.Word word = null;
                            for (int i = 0; i < wordList.size(); i++) {
                                word = wordList.get(i);
                                stringBuilder.append(word.getWords());
                                if (i != wordList.size() - 1) {
                                    stringBuilder.append("\n");
                                }
                            }
                            dismissDialog();
                            PhotoResultActivity.sResult=stringBuilder.toString();
                            startActivity(PhotoResultActivity.class);
                        }
                    });
                }
            }
        });
    }

}